<template>
  <div>
    <vxe-modal
      :title="modalTitle"
      v-model="show"
      :loading="loading"
      :mask="false"
      :lock-view="false"
      width="60vw"
      height="680px"
      destroy-on-close
      show-zoom
      remember
      resize
      show-footer
    >
      <!-- 主体部分： form 表单 -->
      <el-form
        ref="refForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab">
          <!-- 第一选项卡 -->
          <el-tab-pane
            :label="$t('menu.dev.prop.tabs.basic', '基本信息')"
            name="basic"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.label', '标签名称')"
                  prop="label"
                  :tooltipContent="$t('menu.dev.prop.tip.label', '')"
                >
                  <el-input
                    v-model="formData.label"
                    :placeholder="$p('menu.dev.prop.field.label', '标签')"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col :span="24">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.value', '值')"
                  prop="value"
                  :tooltipContent="$t('menu.dev.prop.tip.value', '')"
                  :rules="[
                    {
                      pattern: /^[a-z_]+$/,
                      message: $t('common.validate.only_lower_under'),
                    },
                  ]"
                >
                  <el-input
                    v-model="formData.value"
                    :placeholder="$p('menu.dev.prop.field.value', '值')"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col :span="24">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.type', '类型')"
                  prop="type"
                  :tooltipContent="$t('menu.dev.prop.tip.type')"
                >
                  <ra-dict-select
                    :placeholder="
                      $p('menu.dev.prop.field.type', '字段类型', 'select')
                    "
                    v-model="formData.type"
                    code="sys_prop_type"
                    type="select"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col
                :span="24"
                v-if="formData.type !== 'field' || formData.type !== 'action'"
              >
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.for_template', '页面模板')"
                  prop="for_template"
                  :tooltipContent="$t('menu.dev.prop.tip.for_template')"
                >
                  <ra-dict-select
                    :placeholder="
                      $p(
                        'menu.dev.prop.field.for_template',
                        '页面模板',
                        'select',
                      )
                    "
                    v-model="formData.for_template"
                    code="sys_template"
                    type="select"
                  />
                </el-form-item-plus>
              </el-col>

              <el-col :span="12">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.for_admin', '后端适用')"
                  prop="for_admin"
                  :tooltipContent="$t('menu.dev.prop.tip.for_admin')"
                >
                  <ra-dict-select
                    :placeholder="
                      $p('menu.dev.prop.field.for_admin', '后端适用', 'select')
                    "
                    v-model="formData.for_admin"
                    code="yes_or_not_options"
                    type="radio"
                  />
                </el-form-item-plus>
              </el-col>

              <el-col :span="12">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.for_api')"
                  prop="for_api"
                  :tooltipContent="$t('menu.dev.prop.tip.for_api')"
                >
                  <ra-dict-select
                    :placeholder="
                      $p('menu.dev.prop.field.for_api', 'API适用', 'select')
                    "
                    v-model="formData.for_api"
                    code="yes_or_not_options"
                    type="radio"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col :span="24">
                <el-form-item-plus
                  :label="$t('common.field.remark')"
                  prop="remark"
                >
                  <el-input
                    type="textarea"
                    :rows="6"
                    v-model="formData.remark"
                    :placeholder="$p('common.field.remark', '备注')"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col :span="12">
                <el-form-item-plus :label="$t('common.field.sort')" prop="sort">
                  <el-input-number
                    v-model="formData.sort"
                    controls-position="right"
                    :min="0"
                  />
                </el-form-item-plus>
              </el-col>
              <el-col :span="12">
                <el-form-item-plus
                  :label="$t('common.field.status')"
                  prop="status"
                >
                  <ra-dict-select
                    :placeholder="$p('common.field.status', '状态', 'select')"
                    v-model="formData.status"
                    code="status_options"
                    type="radio"
                  />
                </el-form-item-plus>
              </el-col>
            </el-row>
          </el-tab-pane>
          <!-- 第二选项卡 -->
          <el-tab-pane :label="$t('menu.dev.prop.tabs.config')" name="config">
            <el-row>
              <el-col :span="24">
                <el-form-item-plus
                  :label="$t('menu.dev.prop.field.config')"
                  prop="config"
                  label-position="top"
                >
                  <ra-object-editor v-model="formData.config" />
                </el-form-item-plus>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <!-- end -->
      </el-form>

      <!-- footer -->
      <template #footer>
        <div>
          <el-button type="info" @click="cancelHandler">
            {{ $t('common.action.cancel', '取消') }}
          </el-button>
          <el-button type="warning" @click="resetHandler">
            {{ $t('common.action.reset', '重置') }}
          </el-button>
          <el-button type="primary" @click="submitHandler" :disabled="loading">
            {{ $t('common.action.confirm', '确定') }}
          </el-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup>
// 设置选项式 API 的内容
defineOptions({
  // 组件名称
  name: 'DemoField1Modal',
  // 阻止透传非 props 属性
  inheritAttrs: false,
});
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import PropAPI from '@/api/admin/dev/prop';
import { clone } from 'xe-utils';

// Props定义
const props = defineProps({
  mode: {
    type: String,
    default: 'add',
    validator: (value) => ['add', 'update'].includes(value),
  },
});

// 表单数据是否载入完成
const isLoaded = ref(false);
// 定义可触发事件
const emit = defineEmits(['reload']);
// 是否显示载入效果
const loading = ref(false);
// 是否显示
const show = ref(false);
// 当前Tab
const activeTab = ref('basic');
// 表单对象
const refForm = ref();

// 计算属性：模态框标题
const modalTitle = computed(() => {
  return props.mode === 'add'
    ? $t('common.action.add', '新增')
    : $t('common.action.update', '修改');
});

// 表单数据
const formData = ref({
  id: null,
  label: '',
  value: '',
  type: null,
  config: {},
  for_template: null,
  for_admin: 1,
  for_api: 1,
  remark: null,
  status: 1,
  sort: null,
});

// 初始表单数据（用于重置）
const initialFormData = ref({
  id: null,
  label: '',
  value: '',
  type: null,
  config: {},
  for_template: null,
  for_admin: 1,
  for_api: 1,
  remark: null,
  status: 1,
  sort: null,
});

const formRules = reactive({
  label: [
    {
      required: true,
      message: $t('common.message.validate.required', {
        field: $t('menu.dev.prop.field.label'),
      }),
      trigger: 'blur',
    },
  ],
  value: [
    {
      required: true,
      message: $t('common.message.validate.required', {
        field: $t('menu.dev.prop.field.value'),
      }),
      trigger: 'blur',
    },
  ],
});

/**
 * 方法
 */
// 重置表单
const resetForm = () => {
  if (refForm.value) {
    refForm.value.resetFields();
  }
  // 重置表单数据到初始状态
  Object.assign(formData.value, initialFormData.value);
};

// 初始化表单数据
const initFormData = (data = {}) => {
  Object.assign(formData.value, initialFormData.value, data);
};

/**
 * 操作句柄
 */
// 提交操作（统一处理新增和编辑）
const submitHandler = async () => {
  try {
    await refForm.value.validate();
    loading.value = true;

    const postData = clone(formData.value);
    console.log('Form Data :', postData);

    if (props.mode === 'add') {
      await PropAPI.add(formData.value);
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.add'),
        }),
      );
    } else {
      await PropAPI.update(formData.value);
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.update'),
        }),
      );
    }
    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error(`Error in ${props.mode}Handler:`, error);
    ElMessage.error(
      props.mode === 'add'
        ? $t('common.message.failed.general', {
            action: $t('common.action.add'),
          })
        : $t('common.message.failed.general', {
            action: $t('common.action.update'),
          }),
    );
  } finally {
    loading.value = false;
  }
};

// 取消操作
const cancelHandler = () => {
  resetForm();
  show.value = false;
};

// 重置表单操作
const resetHandler = () => {
  resetForm();
};

/**
 * 暴露方法
 */
defineExpose({
  show(id) {
    if (props.mode === 'add') {
      // 设置所属字典
      if (id) {
        formData.value.menuId = id;
      }
      // 初始化表单数据
      initFormData();
      // 显示组件
      show.value = true;
      // 重置表单
      nextTick(() => {
        resetForm();
        isLoaded.value = true;
      });
    } else {
      // 编辑模式：加载数据
      const params = { id };
      loading.value = true;
      PropAPI.getFormData(params)
        .then(({ data }) => {
          initFormData(data);
          show.value = true;
          nextTick(() => {
            // 重置表单验证状态
            if (refForm.value) {
              refForm.value.clearValidate();
            }
            // 数据是否载入完成
            isLoaded.value = true;
          });
        })
        .catch((error) => {
          console.error('Error loading form data:', error);
          ElMessage.error($t('common.message.info.load_failed'));
        })
        .finally(() => {
          loading.value = false;
        });
    }
  },
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
